from influxdb import InfluxDBClient

from backend.utils import GetYamlData
from backend.utils.settings import ensure_path_sep




class InfluxDBUtils:

    def __init__(self, database: str):
        inflxudb_config = GetYamlData(ensure_path_sep("\\conf\\influx.yaml")).get_yaml_data()['influx']
        self.client = InfluxDBClient(**inflxudb_config)
        self.client.switch_database(database)

    def select(self, query: str):
        res_list = self.client.query(query)
        result_list = []
        vmFaultCount = 0
        vmFreeCount = 0
        vmNormalCount = 0
        vmUsedCount = 0
        vmTotalCount = 0
        for data in res_list:
            for res in data:
                result_list.append(res)
                vmFaultCount += res.get('vm_fault_count')
                vmFreeCount += res.get('vm_free_count')
                vmNormalCount += res.get('vm_normal_count')
                vmUsedCount += res.get('vm_used_count')
                vmTotalCount += res.get('vm_total_count')
        self.client.close()
        return result_list, vmFaultCount, vmFreeCount, vmNormalCount, vmUsedCount, vmTotalCount


if __name__ == '__main__':
    query = "select * from resource_statistic limit 100"
    query = "select * from resource_statistic where region_name = '西南' and time >= '2024-11-01T00:20:00Z'"
    query = "select * from resource_statistic where region_name = '西南' and time = '2024-11-01T10:36:00Z'"
    query = "select * from resource_statistic where time = '2024-11-01T10:36:00Z'"
    InfluxDBUtils('cginstance').select(query)
